import ParseFileUtil from "@/components/util/parseFile.js";
import API from "@/components/data/api.js";
//连接数据库并获取数据
function connectMySQL(settings, op, callback) {
  $.post(API.connectMySql, settings, function(res) {
    if (res.errCode == 0) {
      op.dataList = res.data;
      op.dataList = JSON.parse(decodeURI(JSON.stringify(op.dataList)));
    }
    callback(op);
  });
}

//URL请求获取数据
function doRequest(settings, op, callback) {
  var post = {};
  post.url = settings.url;
  var data = {};
  for (var i = 0; i < settings.params.length; i++) {
    data[settings.params[i].name] = settings.params[i].val;
  }
  post.data = data;
  $.post(post.url, data, function(res) {
    if (res.errCode == "200") {
      ParseFileUtil.arrayFromObj.data = res.data;
      if (ParseFileUtil.arrayFromObj.data instanceof Array) {
        op.dataList = ParseFileUtil.arrayFromObj.data;
      } else if (ParseFileUtil.arrayFromObj.data instanceof Object) {
        ParseFileUtil.arrayFromObj.getArray(ParseFileUtil.arrayFromObj.data);
        op.dataList = ParseFileUtil.arrayFromObj.result;
      }
      op.dataList = JSON.parse(decodeURI(JSON.stringify(op.dataList)));
    }
    callback(op);
  });
}
/**
 * 获取数据包
 * @param {数据包id} id
 * @param {返回数据函数} callback
 */
function loadDataSource(id, callback) {
  console.log("id", id, callback);
  $.post(API.getDataSource, { sourceId: id }, function(res) {
    if (res.errCode == 0 && res.data.length == 1) {
      var data = res.data[0];

      data.title = data.title ? decodeURI(data.title) : "";
      data.detail = data.detail ? decodeURI(data.detail) : "";
      data.source_id = data.source_id;
      data.data_op = JSON.parse(decodeURI(data.data_op));
      data.param = JSON.parse(decodeURI(data.param));

      //数据包类型(1:json,2:mysql,3:url)
      if (data.source_type == 1) {
        data.dataList = data.param;
        callback(data);
      } else if (data.source_type == 2) {
        connectMySQL(data.param, data, callback);
      } else if (data.source_type == 3) {
        doRequest(data.param, data, callback);
      }
    } else {
      callback(null);
    }
  });
}

export default {
  loadDataSource,
  doRequest,
  connectMySQL
};
